package com.twu.biblioteca.ui;

import java.util.ArrayList;
import java.util.List;

public class Menu {
    private final List<MenuItem> menuItemList;
    private List<MenuItem> availableMenuItemList;

    public Menu() {
        menuItemList = new ArrayList<MenuItem>();
    }

    private void countAvailableMenuItemList() {
        availableMenuItemList = new ArrayList<MenuItem>();
        for (MenuItem item : menuItemList) {
            if (item.isAvailable()) {
                availableMenuItemList.add(item);
            }
        }
    }

    public void addItem(MenuItem item) {
        menuItemList.add(item);
    }

    public Boolean verify(String command) {
        try {
            Integer commandAsNumber = Integer.parseInt(command);
            countAvailableMenuItemList();
            if (commandAsNumber <= availableMenuItemList.size()) {
                return true;
            }
            return false;
        } catch (NumberFormatException ex) {
            return false;
        }
    }

    public void input(String command) {
        Integer commandAsNumber = Integer.parseInt(command);
        countAvailableMenuItemList();
        if (commandAsNumber <= availableMenuItemList.size()) {
            MenuItem targetMenuItem = availableMenuItemList.get(commandAsNumber - 1);
            targetMenuItem.actuate();
        }
    }

    public String show() {
        StringBuilder sb = new StringBuilder();
        int index = 1;
        for (MenuItem item : menuItemList) {
            if (item.isAvailable()) {
                sb.append(index).append(".").append(item.getName()).append("\n");
                index++;
            }
        }

        return sb.substring(0, sb.length() - 1);
    }
}
